package com.dmy.ui;

import com.dmy.component.MJPanel;
import com.dmy.component.SimpleSnake;
import com.dmy.component.Snake;
import com.dmy.config.GlobleConfig;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 主启动类
 */
public class MainWindow extends JFrame {

    private MJPanel mjPanel;

    private List<Snake> snakes ;

    public MainWindow(){
        initComponent();
    }

    boolean f = false;
    /**
     * 初始化组件
     */
    private void initComponent() {
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setBounds(GlobleConfig.WINDOW_X,GlobleConfig.WINDOW_Y,GlobleConfig.WINDOW_WIDTH,GlobleConfig.WINDOW_HEIGHT);

        // 监听键盘按下事件
        this.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                switch (e.getKeyCode()){
                    case 45:
                        snakes.forEach(s->s.jianSD());
                        break;
                    case 61:
                        snakes.forEach(s->s.addSD());
                        break;
                    case 32:
                        f=!f;
                        if(f) {
                            snakes.forEach(s->s.stopGame());
                        }else{
                            snakes.forEach(s->s.startGame());
                        }
                        break;
                    case 38:
                    case 87:
                        snakes.get(0).moveUp();
                        break;
                    case 83:
                    case 40:
                        snakes.get(0).moveDown();
                        break;
                    case 65:
                    case 37:
                        snakes.get(0).moveLeft();
                        break;
                    case 39:
                    case 68:
                        snakes.get(0).moveRight();
                        break;
                    default:
                }

            }
        });
        mjPanel = buildMJPanel();
        this.add(mjPanel);
    }

    private MJPanel buildMJPanel() {
        MJPanel mjPanel = new MJPanel();
        Snake snake = new SimpleSnake(mjPanel);
        this.snakes = mjPanel.addSnake(snake);
        return mjPanel;
    }

    public static void main(String[] args) throws InvocationTargetException, InterruptedException {
        EventQueue.invokeAndWait(()->{
            new MainWindow();
        });
    }
}
